package sampleguiplugin;

import gamefw.framework.Coordinate;
import gamefw.gameplugin.AbstractGameLogic;
import gamefw.uiplugin.IInputManager;
import gamefw.uiplugin.IOutputManager;
import gamefw.uiplugin.IUIAbstractFactory;
import gamefw.uiplugin.IUIResourceProperties;
import gamefw.uiplugin.IVisualResource;

import java.awt.Dimension;
import java.lang.reflect.InvocationTargetException;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class SampleGUIAbstractFactory implements IUIAbstractFactory {
	
	private JFrame mainFrame;
	
	private IOutputManager outputManager;
	
	public SampleGUIAbstractFactory() {
	}
	
	@Override public void initialize(AbstractGameLogic gameLogic) {
		final AbstractGameLogic logic = gameLogic;
		try {
			SwingUtilities.invokeAndWait(new Runnable() {
				public void run() {
					createAndShowMainFrame(logic);
				}
			});
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void createAndShowMainFrame(AbstractGameLogic gameLogic) {
		String title = gameLogic.getGameTitle();
		if (title == null) {
			title = "Sample GUI Plugin - Java 2D Platform";
		}
		
		this.mainFrame = new JFrame(title);
		
		Coordinate desiredSize = gameLogic.getScreenSize();
		if (desiredSize == null) {
			desiredSize = new Coordinate(800, 600);
		}
		
		this.mainFrame.getContentPane().setPreferredSize(
				new Dimension(desiredSize.getX(), desiredSize.getY()));
		this.mainFrame.pack();
		
		this.mainFrame.setVisible(true);
	}

	@Override
	public IUIResourceProperties createUIResourceProperties() {
		return new SampleGUIResourceProperties();
	}

	@Override
	public IInputManager createInputManager() {
		return new SampleGUIInputManager(this.mainFrame);
	}

	@Override
	public IOutputManager createOutputManager() {
		this.outputManager = new SampleGUIOutputManager(this.mainFrame); 
		return this.outputManager;
	}

	@Override
	public IVisualResource createVisualResource(String visualResourceName) {
		try {
			return new SampleGUIVisualResource(visualResourceName, this.outputManager);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
